import os
import time
from typing import Dict, List, Optional, Any

import json

# Extracted LLM client and parser
from backend.llm_client import llm_chat, LLMClientError
from backend.llm_parser import parse_fixed_files_from_llm


def _build_prompt(files: Dict[str, str], issues_by_file: Dict[str, List[dict]], user_message: Optional[str], target_issue: Optional[dict]) -> List[dict]:
    sys_msg = (
        "你是代码修复助手。基于给定的文件内容与问题清单，提出具体的修复建议，并给出修复后的完整文件内容。"
        "要求：1) 不得编造不存在的文件；2) 输出关键变更的简短 diff；3) 最后以 END_OF_TASK 作为单独一行结束；"
        "注意：不要仅输出 END_OF_TASK，必须先给出修复内容和结论。"
    )
    user_lines = ["# 文件与问题清单"]
    files_to_include = files
    if target_issue and isinstance(target_issue, dict) and target_issue.get("file") in files:
        fname = target_issue["file"]
        files_to_include = {fname: files[fname]}
        user_lines.append(f"仅针对目标问题优先修复：{target_issue}")

    for name, code in files_to_include.items():
        user_lines.append(f"\n## 文件: {name}\n`````\n{code[:12000]}\n`````")
        issues = issues_by_file.get(name) or []
        if issues:
            user_lines.append("- 问题：")
            for it in issues[:20]:
                user_lines.append(f"  - 行 {it.get('line')}: {it.get('message')} 建议: {it.get('suggestion')}")
    if user_message:
        user_lines.append(f"\n# 用户附加消息\n{user_message}")

    return [
        {"role": "system", "content": sys_msg},
        {"role": "user", "content": "\n".join(user_lines)},
    ]


def run_simple_fix(files: Dict[str, str], issues_by_file: Dict[str, List[dict]], user_message: Optional[str] = None, target_issue: Optional[dict] = None, provider: Optional[str] = None, openai_key: Optional[str] = None) -> Dict[str, Any]:
    messages = _build_prompt(files, issues_by_file, user_message, target_issue)
    chat_history: List[dict] = []
    try:
        # Pass through provider/openai_key overrides to the llm client
        answer = llm_chat(messages, provider=provider, override_openai_key=openai_key)
        chat_history = messages + [{"role": "assistant", "content": answer}]
        # 使用解析器解析修复文件
        fixed_files: List[dict] = parse_fixed_files_from_llm(answer)
        return {"success": True, "chat_history": chat_history, "fixed_files": fixed_files}
    except Exception as e:
        err = str(e)
        if not chat_history:
            chat_history = messages
        chat_history.append({"role": "assistant", "content": f"自动修复失败：{err}"})
        return {"success": False, "error": err, "chat_history": chat_history, "fixed_files": []}
